using System;
using System.Collections;
using Velocity4Net.Errors;
using Velocity4Net.Runtime.Logging;
namespace Velocity4Net.Runtime.Parse.AST
{
    /**
     * SetExecutor that is smart about Maps. If it detects one, it does not
     * use Reflection but a cast to access the setter. 
     *
     * @author <a href="mailto:henning@apache.org">Henning P. Schmiedehausen</a>
     * @version $Id: MapSetExecutor.java 799457 2009-07-30 22:10:27Z nbubna $
     * @since 1.5
     */
    public class MapSetExecutor : SetExecutor
    {
        private String property;

        public MapSetExecutor(Log log, Type clazz, String property)
        {
            this.log = log;
            this.property = property;
            discover(clazz);
        }

        protected void discover(Type clazz)
        {
            if (property != null && typeof(IDictionary).IsAssignableFrom(clazz))
            {
                try
                {
                    Method=(typeof(IDictionary).GetMethod("Item", new Type[] { typeof(Object), typeof(Object) }));
                }
                /**
                 * pass through application level runtime exceptions
                 */
                catch (ApplicationException e)
                {
                    throw e;
                }
                catch (System.Exception e)
                {
                    String msg = "Exception while looking for put('" + property + "') method";
                    log.error(msg, e);
                    throw new VelocityException(msg, e);
                }
            }
        }

        public override Object Execute(Object o, Object arg)
        {
            return ((IDictionary)o)[property] = arg;
        }
    }
}